// 数据管理器 - 负责组件间数据同步和共享
class DataManager {
    constructor() {
        this.state = {
            // 核心业务数据
            metrics: {
                // 访客数据
                todayVisitors: 0,
                visitorsChange: 0,
                pageViews: 0,
                pageViewsChange: 0,
                
                // 留言订阅数据
                newMessages: 0,
                messagesChange: 0,
                emailSubscribers: 0,
                subscribersChange: 0,
                
                // 博客数据
                blogArticles: 0,
                articlesChange: 0,
                blogReads: 0,
                readsChange: 0
            },
            
            // 图表数据
            charts: {
                sales: [],
                regions: []
            },
            
            // 系统状态
            system: {
                currentCurrency: 'CNY',
                currentLanguage: 'zh-CN',
                currentTimeRange: 'day',
                exchangeRates: {
                    'USD': 1.0,
                    'EUR': 0.85,
                    'GBP': 0.73,
                    'CNY': 6.45,
                    'JPY': 110.0
                }
            },
            
            // 表单数据
            forms: {},
            
            // 用户操作状态
            ui: {
                activeFilters: {},
                selectedItems: new Set(),
                loadingStates: {}
            }
        };
        
        this.subscribers = new Map();
        this.updateQueue = new Set();
        this.isUpdating = false;
        this.debounceTimer = null;
    }

    // 订阅数据变化
    subscribe(componentId, callback, dependencies = []) {
        if (!this.subscribers.has(componentId)) {
            this.subscribers.set(componentId, { callback, dependencies });
        }
        
        // 立即执行一次回调以获取初始状态
        this.executeCallback(componentId);
        
        return () => this.unsubscribe(componentId);
    }

    // 取消订阅
    unsubscribe(componentId) {
        this.subscribers.delete(componentId);
    }

    // 设置数据
    setState(path, value, options = {}) {
        const oldValue = this.getState(path);
        
        // 数据验证
        if (!this.validateData(path, value, oldValue)) {
            console.warn(`数据验证失败: ${path}`, value);
            return false;
        }
        
        // 深度合并对象
        if (options.merge && typeof value === 'object' && typeof oldValue === 'object') {
            value = this.deepMerge(oldValue, value);
        }
        
        // 设置新值
        this.setNestedState(path, value);
        
        // 触发更新
        this.scheduleUpdate(path, value, oldValue);
        
        return true;
    }

    // 获取数据
    getState(path, defaultValue = null) {
        const keys = path.split('.');
        let current = this.state;
        
        for (const key of keys) {
            if (current && typeof current === 'object' && key in current) {
                current = current[key];
            } else {
                return defaultValue;
            }
        }
        
        return current !== undefined ? current : defaultValue;
    }

    // 批量设置数据
    batchUpdate(updates) {
        this.isUpdating = true;
        
        try {
            const changedPaths = [];
            
            for (const [path, value] of updates) {
                const oldValue = this.getState(path);
                if (this.validateData(path, value, oldValue)) {
                    this.setNestedState(path, value);
                    changedPaths.push({ path, value, oldValue });
                }
            }
            
            // 批量触发更新
            this.batchScheduleUpdate(changedPaths);
            
        } finally {
            this.isUpdating = false;
        }
    }

    // 数据验证
    validateData(path, newValue, oldValue) {
        const validators = {
            // 访客数据验证
            'metrics.todayVisitors': (v) => typeof v === 'number' && v >= 0,
            'metrics.visitorsChange': (v) => typeof v === 'number' && v >= -100 && v <= 100,
            'metrics.pageViews': (v) => typeof v === 'number' && v >= 0,
            'metrics.pageViewsChange': (v) => typeof v === 'number' && v >= -100 && v <= 100,
            
            // 留言订阅数据验证
            'metrics.newMessages': (v) => typeof v === 'number' && v >= 0,
            'metrics.messagesChange': (v) => typeof v === 'number' && v >= -100 && v <= 100,
            'metrics.emailSubscribers': (v) => typeof v === 'number' && v >= 0,
            'metrics.subscribersChange': (v) => typeof v === 'number' && v >= -100 && v <= 100,
            
            // 博客数据验证
            'metrics.blogArticles': (v) => typeof v === 'number' && v >= 0,
            'metrics.articlesChange': (v) => typeof v === 'number' && v >= -100 && v <= 100,
            'metrics.blogReads': (v) => typeof v === 'number' && v >= 0,
            'metrics.readsChange': (v) => typeof v === 'number' && v >= -100 && v <= 100,
            
            'system.currentCurrency': (v) => ['USD', 'EUR', 'GBP', 'CNY', 'JPY'].includes(v),
            'system.currentLanguage': (v) => ['zh-CN', 'en-US', 'ja-JP', 'ko-KR'].includes(v)
        };
        
        const validator = validators[path];
        if (validator) {
            return validator(newValue);
        }
        
        return true; // 默认通过验证
    }

    // 响应式表单绑定
    bindForm(formId, initialData = {}) {
        this.state.forms[formId] = initialData;
        
        return {
            getValue: (field) => this.getState(`forms.${formId}.${field}`),
            setValue: (field, value) => this.setState(`forms.${formId}.${field}`, value),
            getFormData: () => this.getState(`forms.${formId}`),
            reset: () => this.setState(`forms.${formId}`, initialData)
        };
    }

    // 实时数据同步
    async syncWithServer(endpoint, path, options = {}) {
        const { pollingInterval = 30000, transform } = options;
        
        const syncData = async () => {
            try {
                const response = await fetch(endpoint);
                const data = await response.json();
                const processedData = transform ? transform(data) : data;
                
                this.setState(path, processedData, { 
                    silent: options.silent,
                    merge: options.merge 
                });
                
            } catch (error) {
                console.error(`数据同步失败: ${endpoint}`, error);
                
                if (options.onError) {
                    options.onError(error);
                }
            }
        };
        
        // 立即同步一次
        await syncData();
        
        // 设置轮询
        if (pollingInterval > 0) {
            const intervalId = setInterval(syncData, pollingInterval);
            return () => clearInterval(intervalId);
        }
        
        return () => {};
    }

    // 性能优化：防抖更新
    scheduleUpdate(path, newValue, oldValue) {
        this.updateQueue.add({ path, newValue, oldValue });
        
        if (this.debounceTimer) {
            clearTimeout(this.debounceTimer);
        }
        
        this.debounceTimer = setTimeout(() => {
            this.processUpdateQueue();
        }, 16); // 约60fps
    }

    // 批量更新调度
    batchScheduleUpdate(changes) {
        changes.forEach(change => {
            this.updateQueue.add(change);
        });
        
        if (this.debounceTimer) {
            clearTimeout(this.debounceTimer);
        }
        
        this.debounceTimer = setTimeout(() => {
            this.processUpdateQueue();
        }, 16);
    }

    // 处理更新队列
    processUpdateQueue() {
        if (this.updateQueue.size === 0) return;
        
        const updates = Array.from(this.updateQueue);
        this.updateQueue.clear();
        
        // 按路径分组，避免重复更新
        const groupedUpdates = this.groupUpdatesByDependency(updates);
        
        // 执行更新
        groupedUpdates.forEach(group => {
            this.notifySubscribers(group);
        });
    }

    // 按依赖关系分组更新
    groupUpdatesByDependency(updates) {
        const groups = [];
        const processedPaths = new Set();
        
        updates.forEach(update => {
            if (processedPaths.has(update.path)) return;
            
            const group = [update];
            processedPaths.add(update.path);
            
            // 查找相关路径
            updates.forEach(otherUpdate => {
                if (otherUpdate.path !== update.path && 
                    !processedPaths.has(otherUpdate.path) &&
                    this.arePathsRelated(update.path, otherUpdate.path)) {
                    group.push(otherUpdate);
                    processedPaths.add(otherUpdate.path);
                }
            });
            
            groups.push(group);
        });
        
        return groups;
    }

    // 检查路径是否相关
    arePathsRelated(path1, path2) {
        return path1.startsWith(path2) || path2.startsWith(path1);
    }

    // 通知订阅者
    notifySubscribers(updates) {
        const changedPaths = updates.map(u => u.path);
        
        this.subscribers.forEach((subscriber, componentId) => {
            const shouldUpdate = subscriber.dependencies.some(dep => 
                changedPaths.some(path => path.startsWith(dep))
            );
            
            if (shouldUpdate) {
                this.executeCallback(componentId);
            }
        });
    }

    // 执行回调
    executeCallback(componentId) {
        const subscriber = this.subscribers.get(componentId);
        if (subscriber) {
            try {
                const relevantData = {};
                subscriber.dependencies.forEach(dep => {
                    relevantData[dep] = this.getState(dep);
                });
                
                subscriber.callback(relevantData);
            } catch (error) {
                console.error(`组件 ${componentId} 更新失败:`, error);
            }
        }
    }

    // 工具方法
    setNestedState(path, value) {
        const keys = path.split('.');
        let current = this.state;
        
        for (let i = 0; i < keys.length - 1; i++) {
            const key = keys[i];
            if (!(key in current)) {
                current[key] = {};
            }
            current = current[key];
        }
        
        current[keys[keys.length - 1]] = value;
    }

    deepMerge(target, source) {
        const output = Object.assign({}, target);
        
        if (this.isObject(target) && this.isObject(source)) {
            Object.keys(source).forEach(key => {
                if (this.isObject(source[key])) {
                    if (!(key in target)) {
                        Object.assign(output, { [key]: source[key] });
                    } else {
                        output[key] = this.deepMerge(target[key], source[key]);
                    }
                } else {
                    Object.assign(output, { [key]: source[key] });
                }
            });
        }
        
        return output;
    }

    isObject(item) {
        return item && typeof item === 'object' && !Array.isArray(item);
    }

    // 数据持久化
    saveToLocalStorage(key = 'dashboard-state') {
        try {
            localStorage.setItem(key, JSON.stringify(this.state));
        } catch (error) {
            console.error('数据持久化失败:', error);
        }
    }

    loadFromLocalStorage(key = 'dashboard-state') {
        try {
            const saved = localStorage.getItem(key);
            if (saved) {
                const parsed = JSON.parse(saved);
                this.state = this.deepMerge(this.state, parsed);
                this.triggerGlobalUpdate();
            }
        } catch (error) {
            console.error('加载持久化数据失败:', error);
        }
    }

    // 触发全局更新
    triggerGlobalUpdate() {
        this.subscribers.forEach((subscriber, componentId) => {
            this.executeCallback(componentId);
        });
    }

    // 性能监控
    getPerformanceMetrics() {
        return {
            subscriberCount: this.subscribers.size,
            updateQueueSize: this.updateQueue.size,
            stateSize: JSON.stringify(this.state).length
        };
    }
}

// 创建全局数据管理器实例
window.dataManager = new DataManager();